﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Windows.Forms;
using System.IO;
using System.Net;
using HttpHelper;
using System.Xml;
using System.Xml.Linq;
using System.Collections;
using MesForm.MES;

namespace XWDMes
{
    public class HotpressMesService: IMes
    {
        private string _apiUrl;

        public HotpressMesService(string apiUrl)
        {
            if (string.IsNullOrEmpty(apiUrl))
                throw new ArgumentException("接口地址不能为空", nameof(apiUrl));

            _apiUrl = apiUrl;
        }
        public string GetNewUrl()
        {
            XmlDocument xmlDocument = new XmlDocument();
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "Config\\MesParamConfig.xml";
            xmlDocument.Load(filePath);
            XmlDocument _mesParamOC= xmlDocument;
            foreach (XmlNode MesParamNode in _mesParamOC.SelectNodes("MesConfig/System"))
            {
                return MesParamNode.SelectSingleNode("loginUrl").InnerText.Trim().Replace("/r/n", Environment.NewLine);                
            }
            return null;
        }

        /// <summary>
        /// 异步发送
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public async Task<string> AsyncSendHttpPost(String jsonData)
        {
            try
            {
                if (string.IsNullOrEmpty(_apiUrl)) throw new Exception("接口地址不能为空");
                if (string.IsNullOrEmpty(jsonData)) throw new Exception("JSON数据不能为空");

                using (var client = new HttpClient())
                {
                    var content = new FormUrlEncodedContent(new[]
                    {
                        new KeyValuePair<string, string>("jsonData", jsonData)
                    });
                    string responseString = string.Empty;
                    // 发送请求
                    HttpHelper.HttpHelper.Post(_apiUrl, jsonData, out responseString);
                    var response = await client.PostAsync(_apiUrl, content);
                    //var responseString = await response.Content.ReadAsStringAsync();

                    var result = JObject.Parse(responseString);

                    if (result["status"]?.ToString() == "false")
                    {
                        var errorMsg = result["mes"]?.ToString() ?? "未知错误";
                        MessageBox.Show(errorMsg, "操作失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }

                    return result.ToString(Newtonsoft.Json.Formatting.Indented);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        ///// <summary>
        ///// 同步发送
        ///// </summary>
        ///// <param name="jsonData"></param>
        ///// <returns></returns>
        //public string SendHttpPost(string apiUrl, String jsonData)
        //{
        //    try
        //    {               
        //        if (string.IsNullOrEmpty(apiUrl)) throw new Exception("接口地址不能为空");
        //        if (string.IsNullOrEmpty(jsonData)) throw new Exception("JSON数据不能为空");

        //        using (var client = new HttpClient())
        //        {
        //            var json = jsonData.ToString().Replace("\r\n", "");
        //            var content = new Dictionary<string,string>
        //            {
        //                { "jsonData", json }
        //            };
        //            string responseString = string.Empty;
        //            string urlEncodedData = BuildUrlEncodedData(content);
        //            // 发送请求                    
        //            bool IsSend = HttpHelper.HttpHelper.Post(apiUrl, urlEncodedData, out responseString);
        //            //var response = client.PostAsync(_apiUrl, content);
        //            //var response = client.PostAsync(_apiUrl, content).Result;
        //            //var responseString = response.Content.ReadAsStringAsync().Result;
        //            if (IsSend == false)
        //            {
        //                MessageBox.Show(responseString, "发送失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        //                return null;
        //            }
        //            var result = JObject.Parse(responseString);

        //            //if (result["status"]?.ToString() == "false")
        //            //{
        //            //    var errorMsg = result["mes"]?.ToString() ?? "未知错误";
        //            //    MessageBox.Show(errorMsg, "操作失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        //            //}

        //            return result.ToString(Newtonsoft.Json.Formatting.Indented);
        //        }
        //    }
        //    catch (Exception)
        //    {
        //        throw;
        //    }
        //}
        /// <summary>
        /// 同步发送
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public string Send(string apiUrl, String jsonData)
        {
            try
            {

                if (string.IsNullOrEmpty(apiUrl)) throw new Exception("接口地址不能为空");
                if (string.IsNullOrEmpty(jsonData)) throw new Exception("JSON数据不能为空");

                using (var client = new HttpClient())
                {
                    var content = new FormUrlEncodedContent(new[]
                    {
                    new KeyValuePair<string, string>("jsonData", jsonData)
                });

                    // 同步发送请求
                    var response = client.PostAsync(apiUrl, content).Result;
                    response.EnsureSuccessStatusCode();
                    string responseString = response.Content.ReadAsStringAsync().Result;

                    var result = JObject.Parse(responseString);

                    //if (result["status"]?.ToString() == "false")
                    //{
                    //    var errorMsg = result["mes"]?.ToString() ?? "未知错误";
                    //    MessageBox.Show(errorMsg, "操作失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    //}

                    return result.ToString(Newtonsoft.Json.Formatting.Indented);
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"请求过程中出现错误: {ex.Message}", ex);
            }
        }
        static string BuildUrlEncodedData(Dictionary<string, string> formData)
        {
            var encodedPairs = new List<string>();

            foreach (var pair in formData)
            {
                string encodedKey = WebUtility.UrlEncode(pair.Key);
                string encodedValue = WebUtility.UrlEncode(pair.Value);
                encodedPairs.Add($"{encodedKey}={encodedValue}");
            }

            return string.Join("&", encodedPairs);
        }
    }

    public class FtpClint
    {
        // FTP 服务器信息
        string ftpServer = "ftp://your-ftp-server.com"; // FTP 服务器地址
        string ftpUsername = "your-username";           // FTP 用户名
        string ftpPassword = "your-password";           // FTP 密码
        string remotePath = "/fixed/path/yourfile.txt"; // FTP 服务器上的固定路径
        string localFilePath = @"C:\path\to\yourfile.txt"; // 本地文件路径

        //try
        //{
        //    // 上传文件
        //    UploadFileToFtp(ftpServer, remotePath, localFilePath, ftpUsername, ftpPassword);   
        //}
        //catch (Exception ex)
        //{   
        //}
        

        static void UploadFileToFtp(string ftpServer, string remotePath, string localFilePath, string username, string password)
        {
            // 创建 FTP 请求
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + remotePath);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential(username, password);

            // 读取本地文件
            byte[] fileContents;
            using (StreamReader sourceStream = new StreamReader(localFilePath))
            {
                fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
            }

            // 设置请求内容长度
            request.ContentLength = fileContents.Length;

            // 上传文件
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(fileContents, 0, fileContents.Length);
            }

            // 获取 FTP 响应
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                Console.WriteLine("上传状态: " + response.StatusDescription);
            }
        }
    }
}

    